package com.tanhua.server.service;

import com.tanhua.dubbo.api.db.*;
import com.tanhua.model.db.Answer;
import com.tanhua.model.db.Questionnaire;
import com.tanhua.model.db.Report;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.enums.Conclusion;
import com.tanhua.model.vo.ReportVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zs
 * @version 1.8
 */
@Service
public class QuestionnaireService {

    //题目服务
    @DubboReference
    private SoulQuestionApi soulQuestionApi;
    //选项服务
    @DubboReference
    private SoulOptionApi soulOptionApi;
    //用户-问卷对应关系表
    @DubboReference
    private UserQuestionnaireApi userQuestionnaireApi;
    //报告服务
    @DubboReference
    private ReportApi reportApi;
    //问卷服务
    @DubboReference
    private QuestionnaireApi questionnaireApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 提交问卷
     *
     * @param Answer
     * @return
     */
    public Long submit( Map<String, List<Answer>> Answer) {

        Integer score = 0;
        //外向得分
        int outGoingScore = 0;
        //判断得分
        int judgeScore = 0;
        //理性得分
        int rationalityScore = 0;
        //抽象得分
        int abstractScore = 0;

        List<Answer> answerList = Answer.get("answers");
        for (Answer answer : answerList) {
            Integer questionId = answer.getQuestionId();
            Integer optionId = answer.getOptionId();
            score = soulOptionApi.findScoreByoptionId(optionId);
            /*
             * 定义四个维度的分数字段,判断questionId是属于哪个类型，就在对应类型的分数加，最后加起来就是总分
             * */
            if ("外向".equals(soulQuestionApi.findTypeByQuestionId(questionId))) {
                outGoingScore += score;
            }
            if ("判断".equals(soulQuestionApi.findTypeByQuestionId(questionId))) {
                judgeScore += score;
            }
            if ("理性".equals(soulQuestionApi.findTypeByQuestionId(questionId))) {
                rationalityScore += score;
            }
            if ("抽象".equals(soulQuestionApi.findTypeByQuestionId(questionId))) {
                abstractScore += score;
            }
        }
        //设置四个维度分数到报告表
        //存double类型到数据库，在vo类进行转换
        //3322 21 21 14 14
        //总分
        int totalScore = outGoingScore + judgeScore + rationalityScore + abstractScore;

        Report report = new Report();
        String characterType =  null;
        //对总分进行判断，确定人格类型
        if (totalScore >= 10 && totalScore < 20) {
        //猫头鹰型
            characterType = "猫头鹰型";
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");
            //枚举类获取
            report.setConclusion(Conclusion.OWL.getType());
            report.setCharacterType(characterType);
        }
        if (totalScore >= 20 && totalScore < 40) {
        //白兔型
            characterType = "白兔型";
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");
            //枚举类获取
            report.setConclusion(Conclusion.RABBIT.getType());
            report.setCharacterType(characterType);
        }
        if (totalScore >= 40 && totalScore < 60) {
        //狐狸型
            characterType = "狐狸型";
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
            //枚举类获取
            report.setConclusion(Conclusion.FOX.getType());
            report.setCharacterType(characterType);
        }
        if (totalScore >=60 && totalScore < 70 ){
        // 狮子型
            characterType = "狮子型";
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");
            //枚举类获取
            report.setConclusion(Conclusion.LION.getType());
            report.setCharacterType(characterType);
        }

        UserInfo userInfo = userInfoApi.findUserInfo(UserHolder.getUserId());
        String gender = userInfo.getGender();

        //调用服务，设置总分和试卷Id还有其他属性到结果表

        int questionId = answerList.get(0).getQuestionId();
        Long questionnaireId = soulQuestionApi.getQuestionnaireId(questionId);
        report.setQuestionnaireId(questionnaireId);
        report.setOutgoing(outGoingScore + 84);
        report.setJudge(judgeScore + 84);
        report.setRationality(rationalityScore + 77);
        report.setAbstraction(abstractScore + 77);
        report.setScore(totalScore);
        report.setUserId(UserHolder.getUserId());
        report.setGender(gender);

        //调用服务，设置report 对象 到 数据库
        Long reportId = reportApi.add(report);
        //解锁下一级问卷（redis）,redis 有数据， 则解锁下一级
        Questionnaire questionnaire = questionnaireApi.findById(questionnaireId);
        String key = "QUESTIONNAIRE_LOCK_" + UserHolder.getUserId();
        String hashKey = questionnaire.getLevel()+1+"";
        stringRedisTemplate.opsForHash().put(key,hashKey,"1");
        //获取结果表的id, 返回给前台
        return reportId;
    }
}
